/*
 * @Author: yangrongxin
 * @Date: 2021-08-13 11:20:37
 * @LastEditors: yangrongxin
 * @LastEditTime: 2021-12-29 15:23:49
 */
import { useEffect, useReducer, useState } from 'react';
import { View, Text, Button, OpenData, Textarea, Input } from '@tarojs/components';
import { AtInput, AtIcon, AtTextarea } from 'taro-ui';
import Taro, { useRouter } from '@tarojs/taro';
import PickerWapper from '@/components/PickerWapper';
import AddressPicker, { getNameDescWithId } from '@/components/PickerWapper/address';
import { getBirthDay } from '@/utils/common';
import { setItemSync } from '@/utils/storage';
import { STORAGE_TYPE } from '@/const/dataDictionary';
import { UserInfoItem } from '../MySetting/components';
import { marriage as marriageList, education as educationList } from './dataDictionary';
import { queryUserDetail, updateUserDetail } from './service';
import { login } from '../../service';
import styles from './index.module.less';

function reducer(state, action) {
  if (action.type === 'update') {
    return {
      ...state,
      ...action.payload,
    };
  }
}

const MyData = () => {
  const {
    params: { isRegister = 'false', phone: propsPhone },
  } = useRouter();

  const [loading, setLoading] = useState<boolean>(false);

  // TODO: 获取当前用户信息的接口
  const [useInfo, updateUserInfo] = useReducer(reducer, {
    // 非必填信息
    marriageStr: '',
    educationStr: '',
    areaStr: '',
    marriage: null,
    education: null,
    area: [],
    // 必填信息
    name: '',
    idCard: '',
    birthDate: '',
    phone: propsPhone,
  });

  const [modalInfo, updateModalInfo] = useReducer(reducer, {
    modalName: '', // 当前弹窗对应的配置字段
    isOpened: false,
    rangeList: [],
    title: '',
  });

  const changeUserInfo = (payload) => {
    updateUserInfo({
      type: 'update',
      payload,
    });
  };

  const changeModalInfo = (payload) => {
    updateModalInfo({
      type: 'update',
      payload,
    });
  };

  useEffect(() => {
    Taro.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#f7f6ff',
    });
    if (isRegister === 'false') {
      setLoading(true);
      console.log('获取用户详情数据');
      queryUserDetail().then((res: any) => {
        const { marriage, education, province, city, area } = res;
        updateUserInfo({
          type: 'update',
          payload: {
            ...res,
            marriageStr: marriageList[marriage],
            educationStr: educationList[education],
            areaStr: getNameDescWithId(province, city, area).join('·'),
            area: [province, city, area],
          },
        });
        setLoading(false);
      });
    }
  }, []);

  const { marriageStr, educationStr, areaStr, name, idCard, birthDate, phone, marriage, education, area } = useInfo;

  const { title, isOpened, rangeList, modalName } = modalInfo;

  /* 注册当前账户的信息 */
  const registerWechat = () => {
    Taro.login().then(({ code }) => {
      login({
        code,
        loginDeviceNum: `${new Date().getTime()}`,
        loginDeviceType: 'WX_APP',
        weChatRequestType: 'MINI_PROGRAM',
        name,
        idCard,
        birthDate,
        marriage,
        education,
        province: area[0],
        city: area[1],
        area: area[2],
      }).then((res: any) => {
        if (res?.userInfo?.accountId) {
          setItemSync(STORAGE_TYPE.USERINFO, res?.userInfo);
          setItemSync(STORAGE_TYPE.TEAMMAINUSER, res?.teamMainUser);
          setItemSync(STORAGE_TYPE.ISLOGIN, 1);
          Taro.reLaunch({
            url: '/pages/Home/index',
          });
        }
        console.log('loginRes', res);
      });
    });
  };

  /* 修改当前用户的数据 */
  const editUserInfo = () => {
    updateUserDetail({
      marriage,
      education,
      province: area[0],
      city: area[1],
      area: area[2],
    }).then((res: any) => {
      if (res) {
        Taro.showToast({
          title: '更新完成！',
          icon: 'none',
        });
        Taro.navigateBack();
      }
    });
  };

  return (
    <View className={styles.container}>
      {/* 展示顶部描述 */}
      <View className={styles.userInfoHeader}>
        <View className={styles.userNotice}>
          <View>
            <Text>个人资料</Text>
            <View></View>
            <View></View>
          </View>
          <Text>绑定后基础资料不可修改</Text>
        </View>
        <View className={styles.openDataHeader}>
          <OpenData type="userAvatarUrl" />
        </View>
      </View>
      {/* 展示必填的基础资料 */}
      <View className={styles.baseInfo}>
        <View className={styles.titleWapper}>
          <Text>基础资料</Text>
          <Text className={styles.purple}>(必填)</Text>
        </View>
        {/* 展示需要进行编辑的内容 */}
        <View className={styles.formContent}>
          {/* <UserInfoItem
            title="姓名"
            rightContent={
              <Input
                name="name"
                type="text"
                value={name}
                disabled={isRegister === 'true'}
                placeholderClass={styles.inputPlaceholder}
                onInput={(e: any) => changeUserInfo({ name: e.detail.value })}
                placeholder="请输入"
              />
            }
          /> */}
          <AtInput
            name="name"
            title="姓名"
            type="text"
            value={name}
            editable={isRegister === 'true'}
            placeholderClass={styles.inputPlaceholder}
            onChange={(value: string) => changeUserInfo({ name: value })}
            placeholder="请输入"
          />
          <AtInput
            name="idCard"
            title="身份证"
            type="text"
            value={idCard}
            editable={isRegister === 'true'}
            placeholderClass={styles.inputPlaceholder}
            placeholder="请输入"
            onChange={(value: string) => changeUserInfo({ idCard: value, birthDate: getBirthDay(value) })}
          />
          <AtInput
            name="birthDate"
            title="生日"
            type="text"
            value={birthDate}
            editable={false}
            placeholder="根据身份证生成"
            placeholderClass={styles.inputPlaceholder}
            onChange={() => undefined}
          />
          <AtInput
            name="phone"
            title="手机号"
            type="number"
            value={phone}
            editable={false}
            placeholder="登录自动获取"
            placeholderClass={styles.inputPlaceholder}
            onChange={() => undefined}
          />
        </View>
      </View>
      {/* 展示选填的其他资料 */}
      <View className={styles.otherInfo}>
        <View className={styles.titleWapper}>
          <Text>其他资料</Text>
          <Text>(选填)</Text>
        </View>
        {/* 展示需要编辑的内容 */}
        <View className={styles.formContent}>
          <AtInput
            className={styles.extendIconClass}
            name="marriageStr"
            title="婚姻"
            value={marriageStr}
            placeholder="请选择"
            placeholderClass={styles.inputPlaceholder}
            type="text"
            onChange={() => undefined}
            editable={false}
            onClick={() => {
              changeModalInfo({
                // isOpened: true,
                rangeList: marriageList,
                title: '请选择您的婚姻状况',
                modalName: 'marriage',
              });
              setTimeout(() => {
                changeModalInfo({
                  isOpened: true,
                });
              }, 200);
            }}
          >
            <AtIcon value="chevron-right" color={marriageStr ? '#333' : '#b8b8b8'} />
          </AtInput>
          <AtInput
            className={styles.extendIconClass}
            name="educationStr"
            title="学历"
            value={educationStr}
            placeholder="请选择"
            placeholderClass={styles.inputPlaceholder}
            type="text"
            onChange={() => undefined}
            editable={false}
            onClick={() => {
              changeModalInfo({
                // isOpened: true,
                rangeList: educationList,
                title: '请选择您的教育状况',
                modalName: 'education',
              });
              setTimeout(() => {
                changeModalInfo({
                  isOpened: true,
                });
              }, 200);
            }}
          >
            <AtIcon value="chevron-right" color={educationStr ? '#333' : '#b8b8b8'} />
          </AtInput>
          <AtInput
            className={styles.extendIconClass}
            name="areaStr"
            title="地区"
            value={areaStr}
            placeholder="请选择"
            placeholderClass={styles.inputPlaceholder}
            type="text"
            onChange={() => undefined}
            editable={false}
            onClick={() => {
              changeModalInfo({ rangeList: [], title: '请选择您所在的地区', modalName: 'area' });
              setTimeout(() => {
                changeModalInfo({
                  isOpened: true,
                });
              }, 200);
            }}
          >
            <AtIcon value="chevron-right" color={areaStr ? '#333' : '#b8b8b8'} />
          </AtInput>
        </View>
      </View>
      {/* 保存按钮 */}
      <Button
        className={!name || !birthDate ? styles.disabled : ''}
        disabled={!name || !birthDate}
        onClick={isRegister === 'true' ? registerWechat : editUserInfo}
      >
        {isRegister === 'true' ? '注册' : '保存'}
      </Button>
      {/* 存放当前展示的弹窗 */}
      <PickerWapper
        title={title}
        isOpened={isOpened && modalName !== 'area'}
        rangeList={rangeList}
        indexValue={useInfo[modalName]}
        onClose={() => changeModalInfo({ isOpened: false })}
        onChange={(val: string, valIndex: number) => {
          changeUserInfo({ [modalName]: valIndex, [`${modalName}Str`]: val });
          changeModalInfo({ isOpened: false });
        }}
      />
      {!loading && (
        <AddressPicker
          isOpened={isOpened && modalName === 'area'}
          title={title}
          indexValue={area}
          onClose={() => changeModalInfo({ isOpened: false })}
          onChange={(val: string[], valIndex: number[]) => {
            changeUserInfo({ [modalName]: valIndex, [`${modalName}Str`]: val.join('·') });
            changeModalInfo({ isOpened: false });
          }}
        />
      )}
    </View>
  );
};

export default MyData;
